<?php

namespace App\Service\Index;

use App\Model\AppVersion;
use App\Model\UserProfile;
use App\Service\BaseService;

/**
 * 版本检测
 */
class CheckVersionService extends BaseService
{
    public function handle()
    {
        $channel = $this->request->input('channel', '');
        $profile = UserProfile::getProfile($this->userId);
        //获取不带ID的版本
        $version = AppVersion::getLatest(
            $this->platform,
            $channel,
            $this->appId,
            $profile->role,
            $profile->gender,
            1
        );
        //获取带有用户ID的版本
        $versionV1 = AppVersion::getLatest(
            $this->platform,
            $channel,
            $this->appId,
            $profile->role,
            $profile->gender,
            0
        );
//        if (!$version) return [];
        $update = version_compare($version->new_version, $this->curVersion, '>') ? 1 : 0;
        $force = $this->curVersion < env('VERSION_FORCE_UPDATE', '1.3.0') ? 1 : $version->update_force;
        log_info(__CLASS__."版本更新2".json_encode($versionV1));

        //指定用户强制更新
        if(!empty($versionV1->user_profile_id)){

            //判断两个版本
            $compare = empty($version) || version_compare($versionV1->new_version, $version->new_version, '>') ? 1 : 0;
            if($compare>=1){
                $userIds = explode(',',$versionV1->user_profile_id);
                if(in_array($profile->user_profile_id,$userIds)){

                    $update = version_compare($versionV1->new_version, $this->curVersion, '>') ? 1 : 0;
                    $force = $this->curVersion < env('VERSION_FORCE_UPDATE', '1.3.0') ? 1 : $versionV1->update_force;
                    $version = $versionV1;
                }
            }
        }
        log_info(__CLASS__."版本更新1".json_encode($version));
        $ret = [
            //是否更新：1-更新，0-不更新
            'update' => $update,
            //是否强制：1-强制，0-不强制
            'force' => $force,
            //更新到的版本：1.0.1
            'version' => $version->new_version,
            //版本更新标题
            'title' => $version->update_title,
            //版本更新描述
            'desc' => $version->desc,
            //版本更新链接（安卓）
            'link' => $version->update_link
        ];
        log_user_result($this->userId, $ret);
        return $ret;
    }
}
